# coding=utf-8
import os
import sys
import datetime

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base.settings")

from common.stats import MG_BIGBANG_COLL
from common.account.model.account import Account
from common.pay.model import Pay, PAY_STATUS
from common.transaction.model import Withdraw
from common import orm


def main(date):

    accounts = Account.query.filter((Account.created_at > "2018-01-01 16:00:00") &
                                    (Account.id == 336171)).all()
    accounts = list(accounts)
    user_ids = [account.id for account in accounts]
    fix_user_transaction(user_ids)

    # aid 和 created_at, register_at
    for account in accounts:
        MG_BIGBANG_COLL.user_stats.update({"_id": account.id},
                                          {"$set":
                                  {"created_at": account.created_at,
                                   "register_at": account.created_at,
                                   }})

    # 充值
    recharges = orm.session.query(Pay.user_id, orm.func.sum(Pay.price)) \
        .filter(Pay.user_id.in_(user_ids)) \
        .filter(Pay.status == 2) \
        .group_by(Pay.user_id).all()

    for recharge in recharges:
        user_id, price = recharge[0], recharge[1]
        MG_BIGBANG_COLL.user_stats.update({"_id": user_id}, {"$set": {"recharge.total": float(price)}})

    withdraws = orm.session.query(Withdraw.user_id, orm.func.sum(Withdraw.price)) \
        .filter((Withdraw.user_id.in_(user_ids)) &
                (Withdraw.status != 32)) \
        .group_by(Withdraw.user_id).all()
    for withdarw in withdraws:
        user_id, price = withdarw[0], withdarw[1]
        print price
        MG_BIGBANG_COLL.user_stats.update({"_id": user_id}, {"$set": {"withdraw.total": float(price)}})

    # aid
    aid_datas = MG_BIGBANG_COLL.daily_stats.find({"user_id": {"$in": user_ids}}, {"user_id": 1, "aid": 1})
    for aid_data in aid_datas:
        aid = aid_data.get('aid')
        if aid:
            MG_BIGBANG_COLL.user_stats.update({"_id": aid_data['user_id']}, {"$set": {"aid": aid}})

    # transaction detail


def fix_user_transaction(uids):
    cond = {
        "user_id": {
            '$in': uids
        }
    }
    cursor = MG_BIGBANG_COLL.daily_stats.aggregate([
        {"$match": cond},
        {"$project": {
            "user_id": 1,
            "bonus": 1,
            "win": 1,
            "pay": 1,
            "refund": 1
        }},
        {"$group": {
            "_id": "$user_id",
            "winTotal": {"$sum": "$win.total"},
            "winCount": {"$sum": "$win.count"},
            "bonusTotal": {"$sum": "$bonus.total"},
            "bonusCount": {"$sum": "$bonus.count"},
            "payTotal": {"$sum": "$pay.total"},
            "payCount": {"$sum": "$pay.count"},
            "refundTotal": {"$sum": "$refund.total"},
        }
        },
    ])
    from pprint import pprint
    for c in cursor:
        user = MG_BIGBANG_COLL.user_stats.find({'_id': c.get('_id')})
        game_gain = 0
        for u in user:
            game_gain = u.get('kfc', {}).get('gain_amount', 0) + \
                        u.get('bull', {}).get('gain_amount', 0) + \
                        u.get('lottery', {}).get('gain_amount', 0) + \
                        u.get('fruit', {}).get('gain_amount', 0)
        update_data = {
            'win.total': c.get('winTotal', 0),
            'win.count': c.get('winCount', 0),
            'bonus.total': c.get('bonusTotal', 0),
            'bonus.count': c.get('bonusCount', 0),
            'pay.total': c.get('payTotal', 0),
            'pay.count': c.get('payCount', 0),
            'refund.total': c.get('refund', 0),
            'gain.total': c.get('winTotal', 0) + c.get('bonusTotal', 0) - c.get('payTotal', 0),
            'total_gain': game_gain + c.get('winTotal', 0) + c.get('bonusTotal', 0) - c.get('payTotal', 0)
        }
        pprint(update_data)
        MG_BIGBANG_COLL.user_stats.update(
            {'_id': int(c.get('_id'))}, {
                '$set': update_data
            })


if __name__ == '__main__':
    if len(sys.argv) > 1:
        date = sys.argv[1] + " 16:00:00"
    else:
        date = "2018-01-01 16:00:00"
    main(date)
